package indi.liangli;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class ProcesserHandler extends SimpleChannelInboundHandler<Request>  {
    private Map<String, Object> handlerMap;


    public ProcesserHandler(Map<String, Object> handlerMap) {
        this.handlerMap = handlerMap;
    }



    //根据客户端传入的class 类型，根据handlerMap找到对应的bean，反射调用目标方法
    private Object invokeMethod(Request request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> clazz = request.getClazz();
        //map中的key 是clazz_version,如果version 为空默认v1.0
        String version = request.getVersion() == null ? "v1.0" : request.getVersion();
        String className = clazz.getName() + "_" + version;
        Object instance = handlerMap.get(className);
        if(instance == null){
            throw  new RuntimeException("this handlerMap not fonud clazz"+className);
        }

        //这里就先默认为所有方法都是有入参的
        Object[] args = request.getArgs();
        Class[] paramterType = new Class[args.length];
        for(int i = 0;i<args.length;i++){
            paramterType[i] = args[i].getClass();
        }

        //do invoker
        Method method = clazz.getMethod(request.getMethodName(), paramterType);
        Object result = method.invoke(instance, args);
        return result;

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request request) throws Exception {
        Object result = invokeMethod(request);
        ctx.writeAndFlush(result);
        System.out.println("向客户端写 "+result);
        ctx.close();

    }
}
